package com.zhigongtech.core.web.config;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

import javax.servlet.Filter;

import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.mgt.DefaultSessionStorageEvaluator;
import org.apache.shiro.mgt.DefaultSubjectDAO;
import org.apache.shiro.spring.LifecycleBeanPostProcessor;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;

import com.zhigongtech.core.web.jwt.shiro.JwtFilter;
import com.zhigongtech.core.web.jwt.shiro.MyRealm;

import lombok.extern.slf4j.Slf4j;

@Configuration
@Slf4j
public class ShiroConfig {

	@Bean
	public ShiroFilterFactoryBean getShiroFilterFactoryBean(
			@Qualifier("securityManager") DefaultSecurityManager securityManager) {
		ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
		shiroFilterFactoryBean.setSecurityManager(securityManager);

		// 添加自己的过滤器并且取名为jwt
		Map<String, Filter> filterMap = new HashMap<>();
		filterMap.put("jwc", new JwtFilter());
		shiroFilterFactoryBean.setFilters(filterMap);
		shiroFilterFactoryBean.setUnauthorizedUrl("/401");
		/**
		 * <br>
		 * 自定义url规则 http://shiro.apache.org/web.html#urls- anon 不需要认证 authc 需要认证 user
		 * 验证通过或RememberMe登录的都可以
		 *
		 * <br>
		 * 当应用开启了rememberMe时,用户下次访问时可以是一个user,但不会是authc,因为authc是需要重新认证的
		 *
		 * <br>
		 * 顺序从上到下,优先级依次降低
		 */
		Map<String, String> filterRuleMap = new LinkedHashMap<String, String>();
		// 访问401和404页面不通过我们的Filter
		filterRuleMap.put("/401", "anon");
		filterRuleMap.put("/404", "anon");
		// 配置不会被拦截的链接 顺序判断
		filterRuleMap.put("/doc.html", "anon");
		filterRuleMap.put("/login", "anon");
		filterRuleMap.put("/**.js", "anon");
		filterRuleMap.put("/druid/**", "anon");
		filterRuleMap.put("/actuator/**", "anon");
		filterRuleMap.put("/swagger**/**", "anon");
		filterRuleMap.put("/webjars/**", "anon");
		filterRuleMap.put("/v2/**", "anon");

		// 所有的请求通过我们自己的JWT filter
		filterRuleMap.put("/**", "jwc");
//		filterRuleMap.put("/**", "anon");
		shiroFilterFactoryBean.setFilterChainDefinitionMap(filterRuleMap);
		return shiroFilterFactoryBean;
	}

	@Bean(name = "securityManager")
	@DependsOn("lifecycleBeanPostProcessor")
	public DefaultSecurityManager getDefaultSecurityManager(@Qualifier("myRelam") MyRealm myRealm, CacheManager cacheManager) {
		DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
		securityManager.setRealm(myRealm);
		if(cacheManager != null) {
			log.info("Initialization shiro cacheManager................");
			securityManager.setCacheManager(cacheManager);
		}
		/*
		 * 链接：https://juejin.im/post/59f1b2766fb9a0450e755993
		 * 来源：掘金
         * 关闭shiro自带的session，详情见文档
         * http://shiro.apache.org/session-management.html#SessionManagement-StatelessApplications%28Sessionless%29
         */
        DefaultSubjectDAO subjectDAO = new DefaultSubjectDAO();
        DefaultSessionStorageEvaluator defaultSessionStorageEvaluator = new DefaultSessionStorageEvaluator();
        defaultSessionStorageEvaluator.setSessionStorageEnabled(false);
        subjectDAO.setSessionStorageEvaluator(defaultSessionStorageEvaluator);
        securityManager.setSubjectDAO(subjectDAO);

		return securityManager;
	}
	

	@Bean(name = "myRelam")
	public MyRealm getMyRealm() {
		return new MyRealm();
	}

	/**
	 * @description下面的代码是添加注解支持
	 */
	@Bean
	@DependsOn("lifecycleBeanPostProcessor")
	public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator() {
		DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator = new DefaultAdvisorAutoProxyCreator();
		// 强制使用cglib，防止重复代理和可能引起代理出错的问题
		// https://zhuanlan.zhihu.com/p/29161098
		defaultAdvisorAutoProxyCreator.setProxyTargetClass(true);
		return defaultAdvisorAutoProxyCreator;
	}

	@Bean
	public LifecycleBeanPostProcessor lifecycleBeanPostProcessor() {
		return new LifecycleBeanPostProcessor();
	}

	@Bean
	public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(
			DefaultWebSecurityManager securityManager) {
		AuthorizationAttributeSourceAdvisor advisor = new AuthorizationAttributeSourceAdvisor();
		advisor.setSecurityManager(securityManager);
		return advisor;
	}
}
